package com.enjoyread.core.utils;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class JwtUtils {
    /**
     * 生成令牌
     * @param content  令牌携带的数据*/
    public static String createToken(String content){
        //1.实例化对象
        JwtBuilder builder= Jwts.builder();
        //2.设置信息
        builder.signWith(SignatureAlgorithm.HS256,createKey());//设置签名的算法类型和对应的密钥
        builder.setSubject(content);//设置令牌携带的内容
        builder.setId(UUID.randomUUID().toString());//设置唯一id,防止重放攻击
        //3.生成字符串 加密（令牌）
        return builder.compact();
    }
    //生成密钥
    private static Key createKey(){
        KeyGenerator generator = null;
        try {
            generator = KeyGenerator.getInstance ("AES");
            generator.init (128);
            return generator.generateKey ();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
       return null;
    }
}
